<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';

// 引用 DOM 容器
const chartDom = ref(null);
let myChart = null;

// 数据初始化
const option = ref({
  title: {
    text: '传统汽车与新能源汽车销量',
    top:20,
    left: 'center',
    textStyle: {
      color: '#FFFFFF', // 标题颜色设置为白色
      fontSize: 20,
      fontFamily: 'YouYuan',
    },

  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    top: '15%',
    textStyle: {
      color: '#FFFFFF', // 图例文字颜色设置为白色
    },
  },
  grid: {
    top:'25%',
    left: '2%',
    right: '8%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'value',
    axisLabel: {
      color: '#FFFFFF', // x轴标签颜色设置为白色
    },
    axisLine: {
      lineStyle: {
        color: '#FFFFFF', // x轴线条颜色设置为白色
      },
    },
  },
  yAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      color: '#FFFFFF', // y轴标签颜色设置为白色
    },
    axisLine: {
      lineStyle: {
        color: '#FFFFFF', // y轴线条颜色设置为白色
      },
    },
  },
  series: [],
});

// API 请求函数
const fetchData = async () => {
  try {
    const response = await fetch('/api/queryAllSoldEvTimes'); 
    const result = await response.json();

    if (result.code === '200') {
      // 数据处理
      const years = [...new Set(result.data.map((item) => item.year))];
      const evData = result.data
          .filter((item) => item.isEv === 'EV')
          .map((item) => item.unitsSold);
      const gasolineData = result.data
          .filter((item) => item.isEv === 'Gasoline')
          .map((item) => item.unitsSold);

      // 设置图表配置
      option.value.yAxis.data = years;
      option.value.series = [
        {
          name: '新能源汽车',
          type: 'bar',
          data: evData,
          itemStyle: {
            color: '#30e3ca',
          },
        },
        {
          name: '传统汽车',
          type: 'bar',
          data: gasolineData,
          itemStyle: {
            color: '#ffde7d',
          },
        },
      ];

      if (myChart) {
        myChart.setOption(option.value);
      }
    } else {
      console.error('API 数据获取失败:', result.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
  }
};

onMounted(() => {
  myChart = echarts.init(chartDom.value);
  fetchData();
});
</script>

<template>
  <div>
    <div ref="chartDom" style="width: 100%; height: 300px;"></div>
  </div>
</template>

<style scoped>
#chartDom {
  width: 100%;
  height: 300px;
}
</style>
